# In-Memory Template Repository & Loader.
from django.template import loader, TemplateDoesNotExist
_template_repository = dict()

# Registration.
def RegisterTemplate(name, tmpl):
    if isinstance(tmpl, basestring):
        tmpl = TemplateRepresentation(tmpl, name = name)

    assert isinstance(tmpl, TemplateRepresentation)
    _template_repository[name] = tmpl

# Querying.
def get_template_query(template_name, template_dirs = None):
    result = _template_repository.get(template_name)
    if result is not None:
        yield result

def get_template_name(name, kind = 'template'):
    return '%s:%s' % (kind, name)

class TemplateRepresentation(object):
    def __init__(self, template, name = '', kind = ''):
        self._template = template
        self._name = name
        self._kind = kind

    def get_name(self):
        return get_template_name(self._name, kind = self._kind)
    def get_source(self):
        return self._template

    def __repr__(self):
        return '<%s: %s>' % (self.__class__.__name__, self.get_name())

def load_template_source(template_name, template_dirs = None):
    if isinstance(template_name, TemplateRepresentation):
        return template_name.get_source()

    for result in get_template_query(template_name, template_dirs = template_dirs):
        # Return first.
        return (result.get_source(), result.get_name())

    from django import template
    raise template.TemplateDoesNotExist, template_name

load_template_source.is_usable = True

# Installation.
def install():
    ##    from django.template import loader
    ##    existing = loader.template_source_loaders or ()
    ##    if load_template_source not in existing:
    ##        existing += (load_template_source,)
    ##
    ##    loader.template_source_loaders = existing

    ensure_exists()

def ensure_exists():
    # HACK: Make sure that our loader is part of the system loaders,
    # otherwise another part of the site (besides turbine) initiated
    # template subsystem.  We force the reload.
    #
    try: from django.template import loader
    except ImportError: pass
    else:
        try: ldrs = loader.template_source_loaders
        except AttributeError: pass
        else:
            if ldrs is not None and load_template_source not in ldrs:
                # Force reload:
                loader.template_source_loaders = None

            # What if we're not in TEMPLATE_LOADERS setting?
            # Force mechanism to setup custom loaders per application,
            # then insert our own.
            try: loader.find_template('')
            except TemplateDoesNotExist: pass

            # We're pretty sure they're in a tuple by now.
            loader.template_source_loaders += (load_template_source,)
